import React, { useState, useEffect } from 'react';
import ProForm, { ModalForm } from '@ant-design/pro-form';
import { ProColumns, EditableProTable } from '@ant-design/pro-table';
import { Descriptions, Input, Select } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { getShopOrderDetail } from '@/services/shop/api';
import { getLogisticsList } from '@/services/common/api';
import { MsgType, showMsg } from '@/utils/utils';

const OptForm: React.FC<any> = (props) => {
  const { 
    handleModalVisible, 
    handleAdd, 
    actionRef,
    currentRow = {}
  } = props;

  const [goodsList, setGoodsList] = useState<SHOPAPI.ShopGoods[]>([]);
  const [logisticsList, setLogisticsList] = useState<{express_code?: string; express_name?: string;}[]>([]);
  const [expressCode, setExpressCode] = useState<string>('');
  const [deliveryNo, setDeliveryNo] = useState<string>('');
  const [orderDetail, setOrderDetail] = useState<SHOPAPI.ShopOrder>({} as SHOPAPI.ShopOrder);
  const [loading, setLoading] = useState<boolean>(false);

  const columns: ProColumns<SHOPAPI.ShopGoods>[] = [
    {
      title: '品牌',
      dataIndex: 'brand_name'
    },
    {
      title: '名称',
      dataIndex: 'goods_name'
    },
    {
      title: '编号',
      dataIndex: 'goods_id'
    },
    {
      title: '规格',
      dataIndex: 'specs_desc'
    },
    {
      title: '数量',
      align: 'right',
      dataIndex: 'goods_num'
    }
  ];

  const fetchOrderDetail = async () => {
    try {
      const data: SHOPAPI.ShopOrder = await getShopOrderDetail(currentRow.order_id)
      setOrderDetail(data);
      setGoodsList(data.order_goods_list || []);
    } catch (error) {
      showMsg(error?.data?.errmsg);
    }
  }

  useEffect(() => {
    if (currentRow.order_id) {
      fetchOrderDetail();
    }
  }, [currentRow]);

  useEffect(() => {
    getLogisticsList().then((data: { express_code: string; express_name: string;}[]) => {
      setLogisticsList(data);
    })
  }, []);

  const onDevlieryChange = (value: string) => {
    setDeliveryNo(value);
  }

  return <ModalForm
      className="modal-form delivery-modal-form"
      layout="inline"
      width="70%"
      title="订单发货"
      visible
      onVisibleChange={handleModalVisible}
      onFinish={async (value) => {
        const params = {
          mail_id: expressCode,
          mail_name: logisticsList.find(item => item.express_code === expressCode)?.express_name,
          mail_no: deliveryNo,
          order_id: orderDetail.order_id
        }
        if (!params.mail_id) {
          showMsg('请选择快递公司', MsgType.INFO)
          return
        }
        if (!params.mail_no) {
          showMsg('请输入快递单号', MsgType.INFO)
          return
        }
        if (loading) {
          return
        }
        setLoading(true);
        const success = await handleAdd(params);
        setLoading(false);
        if (success) {
          handleModalVisible(false);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }
      }}
      submitter={{
        searchConfig: {
          resetText: '取消',
          submitText: '确定'
        },
        submitButtonProps: {
          loading
        }
      }}>
      <ProForm.Group label="订单物流信息">
        <Descriptions column={3} bordered>
          <Descriptions.Item label="订单编号">{orderDetail.order_id}</Descriptions.Item>
          <Descriptions.Item label="收货人">{orderDetail.receiver}</Descriptions.Item>
          <Descriptions.Item label="手机号码">{orderDetail.receiver_mobile}</Descriptions.Item>
          <Descriptions.Item span={3} label="收货地址">{orderDetail.receiver_address}</Descriptions.Item>
          <Descriptions.Item span={3} label="订单备注">{orderDetail.remarks}</Descriptions.Item>
          <Descriptions.Item label="快递公司">
            <Select 
              placeholder="请选择快递公司" 
              style={{width: '100%'}} 
              onChange={(value: string) => { setExpressCode(value) }}>
              {
                logisticsList.map(item => {
                  return <Select.Option 
                    key={item.express_code} 
                    value={item.express_code as string}>{item.express_name}</Select.Option>
                })
              }
            </Select>
          </Descriptions.Item>
          <Descriptions.Item label="物流单号">
            <Input value={deliveryNo} onChange={(e) => onDevlieryChange(e.target.value)} placeholder="请输入物流单号" />
          </Descriptions.Item>
        </Descriptions>
      </ProForm.Group>

      <ProForm.Group label="商品信息">
        <EditableProTable<SHOPAPI.ShopGoods>
          rowKey="record_id"
          bordered
          value={goodsList}
          dataSource={goodsList}
          columns={columns}
          recordCreatorProps={false}
        />
      </ProForm.Group>
      <ProForm.Group>
        <div className="modal-tips">
          <ExclamationCircleOutlined />
          <span>填写物流单据核对无误后，请点击下方<strong>确定</strong>按钮保存结果</span>
        </div>
      </ProForm.Group>
    </ModalForm>
}
export default OptForm;
